package com.gframework.boot.mvc.controller.protocal;

import java.io.File;
import java.io.FileNotFoundException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

import com.gframework.boot.mvc.controller.protocal.basic.FileResponse;


/**
 * File类型拦截器，如果controller返回一个File，则直接下载文件.
 * 
 * @since 1.0.0
 * @author Ghwolf
 */
@ConditionalOnMissingBean(FileValueInterceptor.class)
public class FileValueInterceptor implements ControllerReturnValueInterceptor{
	private static final Logger logger = LoggerFactory.getLogger(FileValueInterceptor.class);

	public FileValueInterceptor(){
		logger.info("====> 已启用 FileValueInterceptor，controller直接返回file即可下载文件！");
	}
	
	@Override
	public boolean supportInterceptor(Class<?> returnValueType) {
		return File.class.isAssignableFrom(returnValueType);
	}

	@Override
	public Object doInterceptor(Object obj) {
		try {
			return FileResponse.create((File)obj);
		} catch (FileNotFoundException e) {
			if (logger.isWarnEnabled()) {
				logger.warn("{}是一个不存在的文件。",((File) obj).getName(),e);
			}
			return obj ;
		}
	}

	@Override
	public int getOrder() {
		return 1000;
	}

}
